package nix.bs.service;

import java.sql.SQLException;
import java.util.List;

import nix.bs.dao.OrderDao;
import nix.bs.domain.Order;
import nix.jdbc.JdbcUtils;

public class OrderService {

	private OrderDao orderDao = new OrderDao();

	/**
	 * 生成订单（使用事务）
	 */
	public void add(Order order) {
		try {
			JdbcUtils.beginTranscation();
			orderDao.add(order);
			orderDao.addOrderItemList(order.getOrderItemList());
			JdbcUtils.commitTranscation();
		} catch (SQLException e) {
			try {
				JdbcUtils.rollbackTranscation();
			} catch (SQLException e1) {
			}
			throw new RuntimeException(e);
		}
	}

	/**
	 * 我的订单
	 */
	public List<Order> myOrders(String uid) {
		return orderDao.findByUid(uid);
	}

	/**
	 * 按oid查询订单
	 */
	public Order load(String oid) {
		return orderDao.findByOid(oid);
	}

	/**
	 * 确认收货
	 */
	public void confirm(String oid) throws OrderException {
		int state = orderDao.getStateByOid(oid);
		if (state != 3) {
			throw new OrderException("确认收货失败！订单状态异常。");
		}
		orderDao.updateState(oid, 4);
	}

	/**
	 * 支付
	 */
	public void pay(String oid) {
		int state = orderDao.getStateByOid(oid);
		if (state == 1) {
			orderDao.updateState(oid, 2);
		}
	}

	/**
	 * 所有订单
	 */
	public List<Order> findAll() {
		return orderDao.findAll();
	}

	/**
	 * 按状态查询订单
	 */
	public List<Order> findByState(int state) {
		return orderDao.findByState(state);
	}

	/**
	 * 确认发货
	 */	
	public void deliver(String oid) throws OrderException {
		int state = orderDao.getStateByOid(oid);
		if (state != 2) {
			throw new OrderException("确认发货失败！订单状态异常。");
		}
		orderDao.updateState(oid, 3);
	}
}
